from flask import render_template, redirect, request, jsonify, current_app, session, g, abort

from info import db, constants
from info.models import Category, News, User
from info.utils.captcha.response_code import RET
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from . import profile_blu

@profile_blu.route('/info')
@user_login_data
def user_info():

    user=g.user

    if not user:
        return redirect('/')

    data={
        "user":user.to_dict()
    }
    return render_template('news/user.html',data=data)

@profile_blu.route('/base_info',methods=['POST','GET'])
@user_login_data
def base_info():
    '''
    用户基本信息实现
    获取用户登录信息
    获取到传入参数
    更新并保存数据
    返回结果
    :return:
    '''

    # 获取用户信息
    user = g.user
    if request.method=='GET':
        # 获取信息操作
        data={
            'user':g.user.to_dict()
        }
        return render_template('news/user_base_info.html',data=data)


    # 提交数据操作
    # 获取传入参数
    nick_name=request.json.get('nick_name')
    gender=request.json.get('gender')
    signature=request.json.get('signature')

    if not all([nick_name,gender,signature]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数传入错误')

    if gender not in ['MAN','WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数格式错误')

    # 更新并保存数据
    user.nick_name=nick_name
    user.gender=gender
    user.signature=signature

    try:
        db.session.commit()
    except Exception as r:
        current_app.logger.error(r)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg='数据上传错误')

    # 将session中保存的数据进行更新
    session['nick_name']=nick_name

    return jsonify(errno=RET.OK, errmsg='OK')

@profile_blu.route('/pic_info',methods=['POST','GET'])
@user_login_data
def pic_info():
    if request.method=='GET':
        return render_template('news/user_pic_info.html',data={'user':g.user.to_dict()})

    # 如果是POST请求表示修改头像
    # 取到上传的图片
    user=g.user

    try:
        avatar=request.files.get("avatar").read()
    except Exception as r:
        current_app.logger.error(r)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    # 上传头像
    try:
        # 使.form.min.js用自己封装的storage方法去进行图片上传
        key=storage(avatar)
    except Exception as r:
        current_app.logger.error(r)
        return jsonify(errno=RET.THIRDERR,errmsg='上传失败')

    # 保存头像地址
    user.avatar_url = key
    return jsonify(errno=RET.OK,errmsg='OK', data={"avatar_url":constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route('/pass_info',methods=['POST','GET'])
@user_login_data
def pass_info():
    if request.method=='GET':
        return render_template('news/user_pass_info.html',data={'user':g.user.to_dict()})

    # 数据提交逻辑
    '''
    获取数据release
    校验数据
    判断旧密码是否正确
    设置新密码
    '''
    # 获取数据
    old_password=request.json.get('old_password')
    new_password=request.json.get('new_password')

    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    user=g.user

    if not user.check_password(old_password):
        return jsonify(errno=RET.PARAMERR, errmsg='密码输入错误')

    # 输入旧密码正确,给用户设置新密码
    user.password=new_password

    try:
        db.session.commit()
    except Exception as r:
        current_app.logger.error(r)
        return jsonify(errno=RET.DATAERR, errmsg='数据提交失败')

    return jsonify(errno=RET.OK, errmsg='密码修改成功')

@profile_blu.route('/collection',methods=['POST','GET'])
@user_login_data
def user_collection():

    # 获取参数
    page=request.args.get('p',1)
    # 判断参数
    try:
        page=int(page)
    except Exception as r:
        current_app.logger.error(r)
        page=1

    user=g.user

    news_list=[]
    total_page=1
    current_page=1

    try:
        paginate=user.collection_news.paginate(page,constants.USER_FOLLOWED_MAX_COUNT,False)
        current_page=paginate.page
        total_page=paginate.pages
        news_list=paginate.items
    except Exception as r:
        current_app.logger.error(r)

    news_dict_li=[]
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    data={
        "total_page":total_page,
        "current_page":current_page,
        "collections":news_dict_li
    }

    return render_template('news/user_collection.html',data=data)

@profile_blu.route('/news_release',methods=['POST','GET'])
@user_login_data
def news_release():
    # 加载新闻分类数据
    if request.method=='GET':
        categories=[]
        try:
            categories=Category.query.all()
        except Exception as r:
            current_app.logger.error(r)

        category_dict_li=[]
        for category in categories:
            category_dict_li.append(category.to_dict())

        # 移除分类里面最新分类
        category_dict_li.pop(0)

        data={
            "categories":category_dict_li
        }

        return render_template('news/user_news_release.html',data=data)

    # 发布新闻逻辑
    # 获取要提交的数据
    user = g.user

    # 标题
    title=request.form.get('title')
    source='个人发布'
    # 摘要
    digest=request.form.get('digest')
    # 新闻内容
    content=request.form.get('content')
    # 索引图片
    index_image=request.files.get('image')
    # 分类id
    category_id=request.form.get('category')

    # 校验参数
    if not all([title,source,digest,content,index_image,category_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    try:
        category_id=int(category_id)
    except Exception as r:
        current_app.logger.error(r)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 取到图片,将图片上传到七牛云
    try:
        index_image_data=index_image.read()
        key=storage(index_image_data)
        print(key)
    except Exception as r:
        current_app.logger.error(r)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    news=News()

    news.title = title
    news.digest = digest
    news.source=source
    news.content=content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id=category_id
    news.user_id=user.id

    # 1代表审核状态
    news.status=1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as r:
        current_app.logger.error(r)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR,errmsg='数据保存失败')

    return jsonify(errno=RET.OK, errmsg='OK')

@profile_blu.route('/news_list')
@user_login_data
def user_news_list():

    '''
    新闻列表逻辑
    :return:
    '''
    # 获取参数
    page = request.args.get('p', 1)
    # 判断参数
    try:
        page = int(page)
    except Exception as r:
        current_app.logger.error(r)
        page = 1

    user = g.user

    news_list = []
    total_page = 1
    current_page = 1

    try:
        paginate=News.query.filter(News.user_id==user.id).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        news_list=paginate.items
        print(news_list)
        current_page=paginate.page
        total_page=paginate.pages
    except Exception as r:
        current_app.logger.error(r)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_list": news_dict_li
    }
    return render_template('news/user_news_list.html',data=data)

@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    # 获取页数
    p=request.args.get('p',1)
    try:
        p=int(p)
    except Exception as r:
        current_app.logger.error(r)
        p=1

    # 获取当前登录用户

    user=g.user
    follows=[]
    current_page=1
    total_page=1

    try:
        paginate=user.followed.paginate(p,constants.USER_FOLLOWED_MAX_COUNT,False)
        # 获取当前数据
        follows=paginate.items
        current_page=paginate.page
        total_page=paginate.pages
    except Exception as r:
        current_app.logger.error(r)

    user_dict_li=[]
    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())

    data={
        "users":user_dict_li,
        "total_page":total_page,
        "current_page":current_page
    }
    return render_template('news/user_follow.html',data=data)


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    user=g.user
    # 去查询其他人的用户信息
    other_id=request.args.get('user_id')
    if not other_id:
        abort(404)
    other=None
    #查询指定id的用户信息
    try:
        other=User.query.get(other_id)
    except Exception as r:
        current_app.logger.error(r)

    if not other:
        abort(404)

    is_followed=False
    # if 当前新闻有作者,并且当前登录用户已经关注了该用户
    if other and user:
        if other in user.followed:
            is_followed=True

    data={
        "user":user.to_dict() if user else None,
        "other_info":other.to_dict(),
        "is_followed":is_followed
    }

    return render_template('news/other.html',data=data)

@profile_blu.route('/other_news_list')
def other_news_list():
    # 获取页数
    p = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}

    return jsonify(errno=RET.OK, errmsg="OK", data=data)


